package com.movitech.mobile.cz.base.common.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;

import com.movitech.mobile.cz.base.common.security.trustany.TrustAnyHostnameVerifier;
import com.movitech.mobile.cz.base.common.security.trustany.TrustAnyTrustManager; 

public class HttpSSLUtil {


	/**
	 * 向指定URL发送GET方法的请求
	 * 
	 * @param posturl
	 *            发送请求的URL
	 * @param param
	 *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
	 * @return 所代表远程资源的响应结果
	 */
	public static String sendGet(String geturl, String param,String logType) {
		String result = "";
		BufferedReader in = null;
		String urlNameString = geturl + "?" + param;
		URL url;
		try {
			url = new URL(urlNameString);
			// 打开和URL之间的连接
			//System.setProperty("https.protocols", "TLSv1.1");  
            SSLContext sc = SSLContext.getInstance("TLSv1.1");  
            sc.init(null, new TrustManager[] { new TrustAnyTrustManager() }, new java.security.SecureRandom());
            
			HttpsURLConnection conn = (HttpsURLConnection)url.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent",
					"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			// 建立实际的连接
			conn.setSSLSocketFactory(sc.getSocketFactory());  
            conn.setHostnameVerifier(new TrustAnyHostnameVerifier());  
			conn.connect();
			StringBuilder stringBuilder = new StringBuilder();
			int responseCode = conn.getResponseCode();
			if(responseCode==500){
				InputStream errorStream = conn.getErrorStream();
				BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(errorStream));
				String line = null;
				while ((line = bufferedReader.readLine()) != null) {
					stringBuilder.append(line);
				}
				return stringBuilder.toString();
			}
			
			// 获取所有响应头字段
			Map<String, List<String>> map = conn.getHeaderFields();
			// 遍历所有的响应头字段
			for (String key : map.keySet()) {
				System.out.println(key + "--->" + map.get(key));
			}
			// 定义 BufferedReader输入流来读取URL的响应
			in = new BufferedReader(
					new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
			
		} catch (MalformedURLException e) {
			System.out.println("发送GET请求出现异常！" + e);
			e.printStackTrace();
		} catch (IOException e) {
			System.out.println("发送GET请求出现异常！" + e);
			e.printStackTrace();
		} catch (KeyManagementException e) {
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} finally {
			try {
				if (in != null) {
					in.close();
					in = null;
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		System.out.println(result.toString());
		return result;
	}
	
	

	/**
	 * json形式
	 * 
	 * @param posturl
	 * @param obj
	 * @return
	 */
	public static String sendPost(String posturl, String str,String logType) {

		try {
			// 创建连接
			// 打开和URL之间的连接
			//System.setProperty("https.protocols", "TLSv1.1");  
            SSLContext sc = SSLContext.getInstance("TLSv1.1");  
            sc.init(null, new TrustManager[] { new TrustAnyTrustManager() }, new java.security.SecureRandom());
            
			URL url = new URL(posturl);
			HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setRequestMethod("POST");
			connection.setUseCaches(false);
			connection.setInstanceFollowRedirects(true);
			connection.setRequestProperty("Content-Type", "application/json");
			connection.setRequestProperty("RecContentType", "json");
			connection.setRequestProperty("Accept", "application/json");
			
			connection.setSSLSocketFactory(sc.getSocketFactory());  
			connection.setHostnameVerifier(new TrustAnyHostnameVerifier());  
			connection.connect();
			
			// POST请求
			OutputStreamWriter out = new OutputStreamWriter(
					connection.getOutputStream(), "UTF-8");
			out.append(str);
			out.flush();
			out.close();
			
			int responseCode = connection.getResponseCode();
			if(responseCode==500){
				StringBuilder stringBuilder = new StringBuilder();
				InputStream errorStream = connection.getErrorStream();
				BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(errorStream));
				String line = null;
				while ((line = bufferedReader.readLine()) != null) {
					stringBuilder.append(line);
				}
				return stringBuilder.toString();
			}
			
			// 读取响应
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					connection.getInputStream()));
			String lines;
			StringBuffer sb = new StringBuffer("");
			while ((lines = reader.readLine()) != null) {
				lines = new String(lines.getBytes(), "utf-8");
				sb.append(lines);
			}
			reader.close();
			// 断开连接
			connection.disconnect();

			return sb.toString();
		} catch (Exception e) {
			e.printStackTrace();
			return "error";
		}
	}
}
